<template>
	<view style="background-color: #F5F5F5;">
		<nav-bar class="navhead">{{pageTitle}}</nav-bar>
		<view class="stephead">
			<stepInstructions class="step-lay" :stepsData="stepsData" :currentStep="currentStep" />
		</view>

		<scroll-view :style="{height:scrollHeight + 'px'}" :scroll-y="true">

			<entryColumn class="column-root" @onScanFinish="onScanFinish" :entity="item.value" :isScan="item.subCols[0] && item.subCols[0].qrGroup != ''&& item.subCols[0].qrGroup != null && 
					item.subCols[0].qrKey != '' && item.subCols[0].qrKey != null" :qrKey="item.subCols[0].qrKey"
				:qrGroup="item.subCols[0].qrGroup" :groupValue="item.value" v-for="(item,index) in inputAreaGroupData"
				:key="index" :title="item.label">
				<view slot="column-content">
					<input-lay v-for="(subitem,index) in item.subCols" :key="index" :layType="subitem.layType"
						:inputData="subitem" @onInputValueChange="onInputValueChange" :entity="pageEntity"></input-lay>
					<!--  -->
				</view>
			</entryColumn>
			<view style="height: 200upx; background-color: #F5F5F5;" />

		</scroll-view>
		<view class="lay-btn">
			<button class="commit-btn" @click="nextStep" :disabled="!isBtnActive">
				{{(currentStep < stepsData.length -1) ? '下一步': '提交'}}</button>
		</view>
	</view>
</template>

<script>
	import stepInstructions from "@/_components/stepInstructions.vue"
	import testStepInfo from "@/common/commit_data.js"
	import entryColumn from "@/_components/entryColumn.vue"
	import inputLay from "@/_components/inputs/inputLay.vue"
	import checkInputType from "@/utils/checkInputType.js";

	import {
		getColumns,
		createHisData
	} from "@/service/services.js"

	import {
		mapState,
		mapMutations
	} from 'vuex';
	export default {
		components: {
			stepInstructions,
			entryColumn,
			inputLay
		},

		computed: {
			...mapState(['dictionary'])
		},

		data() {
			return {
				scrollHeight: 0,


				pageTitle: "pagetitle",
				pageEntity: '',

				isBtnActive: false,

				originWholeColumnData: [],
				stepColumnData: [],

				inputAreaGroupData: [],

				stepsData: [],
				currentStep: 0,

				// 输入后的值
				reciveInputData: []
			}
		},

		onLoad(option) {
			this.pageTitle = option.pageTitle;
			// this.pageEntity = option.pageEntity;
			this.pageEntity = option.pageEntity;

		},

		onReady() {
			this.genStepsData();
			this.requireColumns(this.pageEntity);

			let that = this;
			uni.getSystemInfo({ //调用uni-app接口获取屏幕高度
				success(res) { //成功回调函数
					let pH = res.windowHeight //windoHeight为窗口高度，主要使用的是这个
					that.scrollHeight = pH
					let titleH = uni.createSelectorQuery().select(".navhead"); //想要获取高度的元素名（class/id）
					titleH.boundingClientRect(data => {
						that.scrollHeight = that.scrollHeight - data.bottom -
							25 //计算高度：元素高度=窗口高度-元素距离顶部的距离（data.top）
					}).exec()

					let stepH = uni.createSelectorQuery().select(".stephead"); //想要获取高度的元素名（class/id）
					stepH.boundingClientRect(data => {
						that.scrollHeight = that.scrollHeight - data.bottom -
							25 //计算高度：元素高度=窗口高度-元素距离顶部的距离（data.top）
					}).exec()
				}
			})

		},

		methods: {
			genStepsData() {
				let tempStepData = null;
				for (let i = 0; i < this.dictionary.length; i++) {
					let itemD = this.dictionary[i];
					if (itemD.value == this.pageEntity) {
						// return itemD;
						tempStepData = itemD.children
						break;
					}
				}

				if (tempStepData != null) {
					tempStepData.forEach(e => {
						if (e.data.icon.substr(0, 1) == "/") {
							e.data.icon = e.data.icon.slice(1)
						}

						if (e.data.actIcon.substr(0, 1) == "/") {
							e.data.actIcon = e.data.actIcon.slice(1)
						}
					})
				}

				if (tempStepData == null)
					this.stepsData = [];
				else {
					this.stepsData = tempStepData;
				}
			},

			genStepColumnData(e) {
				for (let i = 0; i < this.stepsData.length; i++) {
					let tempStepsData = this.stepsData[i]; // step item
					if (tempStepsData.children.length == 0) {
						tempStepsData.subCols = [];
						this.originWholeColumnData.forEach(e => {
							if (e.stepGroup == tempStepsData.value)
								tempStepsData.subCols.push(e)
						})
					} else {
						for (let j = 0; j < tempStepsData.children.length; j++) {
							let tempGroupData = tempStepsData.children[j]
							tempGroupData.subCols = [];
							this.originWholeColumnData.forEach(e => {
								if (e.dataGroup == tempGroupData.value)
									tempGroupData.subCols.push(e)
							})

						}
					}
				}
			},

			requireColumns(e) {
				uni.showLoading()
				getColumns({
					entity: e
				}).then(res => {
					uni.hideLoading()
					console.log(res)
					if (res.code == 0) {
						this.originWholeColumnData = res.data;
						this.genStepColumnData(this.originWholeColumnData);
						this.currentStep = 0;
						this.initInputGroup();
					} else {
						uni.showToast({
							icon: "none",
							mask: true,
							title: res.msg,
						})
						setTimeout(function() {
							uni.navigateBack()
						}, 1000);
					}
				})
			},


			initInputGroup() {
				this.isBtnActive = false;
				this.inputAreaGroupData = [];
				let tempStepData = this.stepsData[this.currentStep];

				if (!tempStepData || !tempStepData.children)
					return;

				if (tempStepData.children.length == 0) {
					this.inputAreaGroupData.push(tempStepData);
				} else {
					this.inputAreaGroupData.push(...tempStepData.children);
				}

				for (let i = 0; i < this.inputAreaGroupData.length; i++) {
					this.inputAreaGroupData[i].subCols.forEach(e => {
						checkInputType.checkInputType(e);
					})
				}

				let item = this.inputAreaGroupData[0].subCols[0];
				console.log("group first =  " + item.qrGroup + " - " + item.qrKey);

				if (item.qrGroup)
					console.log("qrGroup len =  " + item.qrGroup.length);
				if (item.qrKey)
					console.log("qrKey len =  " + item.qrKey.length);
			},

			onScanFinish(inGroup, inQrKey, inQrGroup, inRes) {
				// this.inputAreaGroupData = [];
				let _self = this;
				for (let i = 0; i < this.inputAreaGroupData.length; i++) {
					let tempAreaGroupItem = this.inputAreaGroupData[i];
					if (tempAreaGroupItem.value != inGroup)
						continue;

					tempAreaGroupItem.subCols.forEach(e => {
						e.inputValue = inRes[e.qrKey];

						let finditem = null;
						finditem = _self.reciveInputData.find(function(item) {
							if (item.key == e.name)
								return true;
						})

						if (finditem) {
							finditem.value = e.value;
						} else {
							_self.reciveInputData.push({
								key: e.name,
								value: inRes[e.qrKey]
							});
						}



						// _self.reciveInputData.push({
						// 	key: e.name,
						// 	value: inRes[e.qrKey]
						// })
					})
				}
				this.inputAreaGroupData = JSON.parse(JSON.stringify(this.inputAreaGroupData))
				this.isBtnActive = this.checkGroupIsInputFinish();
			},

			checkGroupIsInputFinish() {
				let isFinish = true;
				let _self = this;
				for (let i = 0; i < this.inputAreaGroupData.length; i++) {
					let tempAreaGroupItem = this.inputAreaGroupData[i];
					tempAreaGroupItem.subCols.forEach(groupItem => {
						if (groupItem.require) {
							let temp = _self.reciveInputData.find((ei) => {
								if (ei.key == groupItem.name) return true;
							})

							if (!temp || !temp.value || temp.value.length <= 0)
								isFinish = false;
						}
					})
				}
				return isFinish;
			},

			nextStep() {
				if (this.currentStep < this.stepsData.length - 1) {
					this.currentStep++;
					this.initInputGroup();
				} else {
					this.reqireCreateHisData();
				}
			},

			/**
			 * 输入数据改变后的回调
			 * @param {Object} e
			 */
			onInputValueChange(e) {
				let finditem = null;
				finditem = this.reciveInputData.find(function(item) {
					if (item.key == e.key)
						return true;
				})

				if (finditem) {
					finditem.value = e.value;
				} else {
					this.reciveInputData.push(e);
				}

				this.isBtnActive = this.checkGroupIsInputFinish()
			},

			reqireCreateHisData() {
				let cols = [];
				let _self = this;

				let tempParam = {
					entityName: this.pageEntity,
					cols: this.reciveInputData
				};

				uni.showLoading();
				let param = JSON.parse(JSON.stringify(tempParam))
				createHisData(param).then(res => {
					uni.hideLoading();
					uni.showToast({
						mask: true,
						title: res.msg,
					})

					if (res.code == 0) {
						setTimeout(function() {
							uni.navigateBack()
						}, 1000);
					}
				})
			}
		}
	}
</script>

<style>
	page {
		background-color: #f7f7f7;
	}
</style>
<style lang="scss" scoped>
	page {
		background-color: #F5F5F5;
	}

	.column-root {
		margin-bottom: 20upx;
		background-color: #fff;
	}

	.step-lay {
		background-color: #fff;
		margin-top: 30upx;
	}

	.commit-btn {
		width: 400upx;
		height: 100upx;
	}

	.lay-btn {
		width: 100%;
		position: absolute;
		bottom: 50upx;
	}
</style>
